package com.study.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.study.dao.OrderMapper;
import com.study.dao.ShopMapper;
import com.study.dao.UserMapper;
import com.study.pojo.entity.Goodsinfo;
import com.study.pojo.entity.Goodstypeinfo;
import com.study.pojo.entity.Orderinfo;
import com.study.pojo.entity.Userinfo;
import com.study.pojo.resp.OrderResp;
import com.study.pojo.resp.ResultMessage;
import com.study.service.ShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import com.study.configs.RedisKeys;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 商城模块业务接口实现类
 * @author Screncea
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Goodsinfo> implements ShopService {
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    ShopMapper shopMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    OrderMapper orderMapper;
    /**
     * 根据商品类型id查询商品信息集合
     * @param goodType 商品类型id
     * @return 商品集合
     */
    @Override
    public ResultMessage selectShopByType(String goodType) {
        //判断redis中是否有商品数据
        Boolean aBoolean = redisTemplate.hasKey(RedisKeys.GOOD_INFO + goodType);
        if (!aBoolean){
            //如果没有该key,则从数据库中查找数据
            List<Goodsinfo> goodsInfoByTypeId = shopMapper.selectShopByType(goodType);
            //非空判断
            if (goodsInfoByTypeId!=null||goodsInfoByTypeId.size()>0){
                //如果不为空,存进redis中
                redisTemplate.opsForList().rightPushAll(RedisKeys.GOOD_LIST+goodType,goodsInfoByTypeId);
            }else {
                //如果为空,防止内存穿透
                List list = new ArrayList();
                list.add("1");
                redisTemplate.opsForList().rightPushAll(RedisKeys.GOOD_LIST+goodType,list);
                //设置失效时间
                redisTemplate.expire(RedisKeys.GOOD_LIST+goodType,60, TimeUnit.SECONDS);
            }
        }
        //如果redis中有数据,则从redis中获取数据
        List list = redisTemplate.opsForList().range(RedisKeys.GOOD_INFO + goodType, 0, -1);
        return new ResultMessage(1,"success",list,list.stream().count());
    }

    /**
     * 判断用户积分是否足够
     * @param totalMoney 商品加积分
     * @return result结果集
     */
    @Override
    public ResultMessage findScore(Integer totalMoney, String userId) {
        //查询用户的积分数量
        Userinfo user  = userMapper.selectIntegral(userId);
        Double userIntegral = user.getUserIntegral();

        if(userIntegral>=totalMoney){
            return new ResultMessage().SUCCESS();
        }
        return  new ResultMessage().SUCCESS().ERROR();
    }

    /**
     * 用户支付
     * @param userPassword 用户输入密码
     * @param userId 用户id
     * @return
     */
    @Transactional
    @Override
    public ResultMessage pay(String userPassword, String userId,String goodId,String orderId) {

      //比对用户密码
        Userinfo user = userMapper.selectIntegral(userId);
        if (!user.getUserPassword().equals(userPassword)){
            return new ResultMessage().ERROR();
        }else{
            //通过商品id查询商品的价格
            Goodsinfo goodByGoodId = shopMapper.findGoodByGoodId(goodId);
            Double goodPrice = goodByGoodId.getGoodPrice();
            int pay = userMapper.pay(userId, goodPrice);
            //将订单状态修改为1,并且添加取件码
            String code = UUID.randomUUID().toString();
            orderMapper.updateStatus(orderId,code);
            return new ResultMessage(1,"success",code,null);
        }

    }

    /**
     * 添加订单
     * @param goodId 商品id
     * @param userId 用户id
     * @return
     */
    @Override
    public ResultMessage addOrder(String goodId, String userId) {
        if (goodId!=null||goodId!=null){
            Orderinfo orderinfo = new Orderinfo();
            String code =UUID.randomUUID().toString();
            orderinfo.setId(code);
            orderinfo.setUserId(userId);
            orderinfo.setGoodId(goodId);
            orderinfo.setOrderStatus(0);
            int i = orderMapper.addOrder(orderinfo);
            return new ResultMessage(1,"success",code,null);
        }
       return  new ResultMessage().ERROR();
    }

    /**
     * 查找支付成功订单的信息
     * @param code 取件码(唯一)
     * @param request 获取用户id
     * @return
     */
    @Override
    public ResultMessage findSuccessOrder(String code, HttpServletRequest request) {
        //获取用户id
        Cookie[] cookie = request.getCookies();
        String userId = null;
        for (Cookie cookie2 : cookie) {
            String name = cookie2.getName();
            if ("userId".equals(name)) {
                userId = cookie2.getValue();
                break;
            }
        }
        //获取用户支付成功的订单信息
        Orderinfo successOrder = orderMapper.findSuccessOrder(code, userId);
        //获取订单商品id
        String goodId = successOrder.getGoodId();
        //通过商品id查找商品的信息
        Goodsinfo goodByGoodId = shopMapper.findGoodByGoodId(goodId);
        OrderResp orderResp = new OrderResp(successOrder.getOrderCode(), successOrder.getId(), goodByGoodId.getGoodName(), goodByGoodId.getGoodCover(), goodByGoodId.getGoodPrice());
        return new ResultMessage(1,"success",orderResp,null);
    }

    /**
     * 查询商品分类
     * @return 分类集合
     */
    @Override
    public ResultMessage selectShopType() {
        //判断redis中是否存在商品分类
        Boolean aBoolean = redisTemplate.hasKey(RedisKeys.TYPE_INFO);
        //判空
        if (!aBoolean){
            //如果没有数据从数据库中查找数据
            List<Goodstypeinfo> goodsTypeInfo = shopMapper.selectShopType();


            //判空
            if (goodsTypeInfo!=null||goodsTypeInfo.size()>0){
                //如果不为空,存进redis中
                redisTemplate.opsForList().rightPushAll(RedisKeys.TYPE_INFO,goodsTypeInfo);
            }else{
                //如果为空,防止内存穿透
                List list = new ArrayList();
                list.add("1");
                redisTemplate.opsForList().rightPushAll(RedisKeys.TYPE_INFO,list);
                //设置失效时间
                redisTemplate.expire(RedisKeys.TYPE_INFO,60, TimeUnit.SECONDS);
            }
        }
        //如果redis中不为空,则从redis中获取数据
        List typeList = redisTemplate.opsForList().range(RedisKeys.TYPE_INFO, 0, -1);
        return new ResultMessage(1,"success",typeList,typeList.stream().count());
    }

    /**
     * 根据商品信息查询商品信息
     * @param  goodId 商品id
     * @return 商品信息
     */
    @Override
    public ResultMessage findGoodByGoodId(String goodId) {
        //查询redis中是否有该商品信息
        Boolean aBoolean = redisTemplate.opsForHash().hasKey(RedisKeys.GOOD_INFO, goodId);
        if (!aBoolean){
            //如果不存在,去数据库查询该商品信息存入redis中
            Goodsinfo goodByGoodId = shopMapper.findGoodByGoodId(goodId);

            String goodImages = goodByGoodId.getGoodImages();
            String[] split = goodImages.split(",");
            List<String> list = new ArrayList();
            for(int i= 0;i<split.length ; i++){
                list.add(split[i]);
            }
            goodByGoodId.setGoodImage(list);
            for (String i: list
                 ) {
                System.out.println(i);
            }
            if (goodByGoodId!=null){
                //如果不为null,存入redis中
                redisTemplate.opsForHash().put(RedisKeys.GOOD_INFO,goodId,goodByGoodId);
            }else {
                // TODO 如果为空,防止内穿透
                redisTemplate.opsForHash().put(RedisKeys.GOOD_INFO,goodId,"");
                //设置失效时间
                redisTemplate.expire(RedisKeys.GOOD_INFO,60, TimeUnit.SECONDS);
            }
        }
        //如果redis中有数据的话,从redis中获取数据
        Object o = redisTemplate.opsForHash().get(RedisKeys.GOOD_INFO, goodId);
        if (StringUtils.isEmpty(o.toString())){
            return new ResultMessage().ERROR();
        }
        return new ResultMessage(1,"success",o,null);
    }

    public ResultMessage selectAllGoods() {
        //判断redis中是否有商品数据
        Boolean aBoolean = redisTemplate.hasKey(RedisKeys.GOOD_LIST);
        if (!aBoolean){
            //如果没有该key,则从数据库中查找数据
            List<Goodsinfo> goodsInfo = shopMapper.selectAllGoods();
            //非空判断
            if (goodsInfo!=null||goodsInfo.size()>0){
                //如果不为空,存进redis中
                redisTemplate.opsForList().rightPushAll(RedisKeys.GOOD_LIST,goodsInfo);
            }else {
                //如果为空,防止内存穿透
                List list = new ArrayList();
                list.add("1");
                redisTemplate.opsForList().rightPushAll(RedisKeys.GOOD_LIST,list);
                //设置失效时间
                redisTemplate.expire(RedisKeys.GOOD_LIST,60, TimeUnit.SECONDS);
            }
        }
        //如果redis中有数据,则从redis中获取数据
        List list = redisTemplate.opsForList().range(RedisKeys.GOOD_LIST, 0, -1);
        return new ResultMessage(1,"success",list,list.stream().count());
    }
}
